<?php

include 'functions.php';

$ch = curl_init();

/*
 * step1 - get form (hidden fields)
 */
//curl_setopt_array($ch, array(
//	CURLOPT_USERAGENT       => "Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.0.4) Gecko/2008102920 AdCentriaIM/1.7 Firefox/3.0.4",
//	CURLOPT_URL             => 'https://ihelper.mts.by/SelfCare',
//	CURLOPT_SSL_VERIFYPEER  => false, // mts https off
//	CURLOPT_SSL_VERIFYHOST  => false, // mts https off
//	CURLOPT_RETURNTRANSFER  => 1,
//	CURLOPT_FOLLOWLOCATION  => 1,
//));
//$out1 = curl_exec($ch);
//echo $out1;
//exit;

/*
 * step2 - login
 */
$url2 = 'https://ihelper.mts.by/SelfCarePda/Security.mvc/LogOn?returnLink=https%3A%2F%2Fihelper.mts.by%2FSelfCarePda%2FHome.mvc';
curl_setopt_array($ch, array(
	CURLOPT_URL             => $url2,
	CURLOPT_HEADER          => 0,
	CURLOPT_RETURNTRANSFER  => 1,
	CURLOPT_FOLLOWLOCATION  => 1,
	CURLOPT_CONNECTTIMEOUT  => 30,
	CURLOPT_SSL_VERIFYPEER  => false, // mts https off
	CURLOPT_SSL_VERIFYHOST  => false, // mts https off

	CURLOPT_POST            => 1,
	CURLOPT_POSTFIELDS      => array(
		'username' => '295985948',
		'password' => '2652301',
		),
	CURLOPT_COOKIEJAR       => dirname(__FILE__).'/cookie.tmp',
	CURLOPT_COOKIE          => dirname(__FILE__).'/cookie.tmp',

));

$out2 = curl_exec($ch);

/*
 * step3 - get page 'состояние счета'
 */
curl_setopt_array($ch, array(
	CURLOPT_URL         => 'https://ihelper.mts.by/SelfCarePda/Account.mvc/Status',
));

$out3 = curl_exec($ch);

/*
	 * step4 - logout
	 */
curl_setopt_array($ch, array(
	CURLOPT_URL         => 'https://ihelper.mts.by/SelfCarePda/Security.mvc/LogOff',
));
curl_exec($ch);


/*
 * grab data
 *
 */

$data3 = array(
	'added_at' => time(),
	'balance'  => '',
	'traffic'  => '',
	'minutes'  => '',
);
preg_match('/баланс.*<strong>(\d*\.\d*)<\/strong>/', $out3, $match);
$data3['balance'] = (int)$match[1];
preg_match('/(\d*,\d*)\sМБ/', $out3, $match);
$data3['traffic'] = (int)$match[1];
preg_match('/(\d*,\d*)\sмин/', $out3, $match);
$data3['minutes'] = (int)$match[1];

dump($data3);
//exit;


/*
 * pub data to SQLITE
 */

//$st = $dbh->prepare("INSERT INTO table2 (added_ts, balanse, mb, min) VALUES (?, ?, ?, ?)");
//$st->execute($data3);
$dbh = new PDO('sqlite:'.
	dirname(__FILE__).DIRECTORY_SEPARATOR.
	'data'.DIRECTORY_SEPARATOR.
	'mts.sqlite');

$sql = "INSERT INTO table2
	(added_date, added_ts, balanse, mb, min)
	VALUES
	(datetime('now','localtime'), ".implode(',',$data3).")
	";
//echo $sql;
$st = $dbh->exec($sql);

$st = $dbh->query('
	SELECT *
	FROM table2
	ORDER BY added_date DESC
	LIMIT 3');
$aRows = $st->fetchAll(PDO::FETCH_ASSOC);

dump($aRows);

// comment tmp1